package bc.swim2.web.servlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bc.swim2.ejb.entity.RegisteredUser;
import bc.swim2.ejb.session.RegistrationBeanRemote;

/**
 * Servlet implementation class RegistrationServlet
 */
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Context ctx;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistrationServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {

			ctx = new InitialContext();
			RegisteredUser reguser = new RegisteredUser();
			Object ref2 = ctx.lookup("RegistrationBean/remote");
			RegistrationBeanRemote regbean = (RegistrationBeanRemote) ref2;

			try {
				reguser.setUsername(request.getParameter("username"));
				reguser.setPassword(request.getParameter("password"));
				reguser.setFirstName(request.getParameter("firstname"));
				reguser.setLastName(request.getParameter("lastname"));
				reguser.setEmail(request.getParameter("email"));
				reguser.setBirthDate(request.getParameter("birthdate"));
			} catch (Exception e) {
				e.printStackTrace();
			}

			boolean isAlreadyRegistered = regbean.isAlreadyRegistered(reguser);

			if (!(isAlreadyRegistered)) {
				regbean.register(reguser);
				response.sendRedirect("MainServlet?to=Index");
			} else {
				request.setAttribute("registrationFailed", true);
				request.getRequestDispatcher("Registration.jsp").forward(
						request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
